# coding: utf-8
from PIL import Image, ImageFont, ImageDraw
from handright import Template, handwrite
from multiprocessing import Pool
import numpy as np

text = "#include <stdio.h>\n" \
       "\n" \
       "int main(void)\n" \
       "{\n" \
       "    printf(\"Hello World!\");\n"\
       "    return 0;\n" \
       "}"

class Text():

    def __init__(self, Grid):
        self.Grid = Grid
        self.Text_background_x = 169*20
        self.Text_background_y = 252*20
        self.Text_background = Image.new(mode="1", size=(self.Text_background_x, self.Text_background_y), color=1)
        self.Text_x_Adjust = 0.0                # 字体X微调
        self.Text_y_Adjust = 0.0                # 字体Y微调
        self.Text_font_size = 8*20
        self.Text_font_dir = "../fonts/把孤单当做晚餐.ttf"
        self.Text_font = ImageFont.truetype(self.Text_font_dir, size=self.Text_font_size)
        self.Text_line_spacing = 14*20          # 行高度
        self.Text_left_margin = 16*20           # 左边距   #600
        self.Text_top_margin = 10*20            # 上边距   #820
        self.Text_right_margin = 24*20          # 右边距   #600
        self.Text_bottom_margin = 48*20         # 下边距   #550
        self.Text_word_spacing = 1              # 字间距
        self.Text_line_spacing_sigma = 3        # 行间距随机扰动
        self.Text_font_size_sigma = 3           # 字体大小随机扰动
        self.Text_word_spacing_sigma = 3        # 字间距随机扰动
        self.Text_end_chars = "，。"             # 防止特定字符因排版算法的自动换行而出现在行首
        self.Text_perturb_x_sigma = 1           # 笔画横向偏移随机扰动
        self.Text_perturb_y_sigma = 1           # 笔画纵向偏移随机扰动
        self.Text_perturb_theta_sigma = 0.05    # 笔画旋转偏移随机扰动

        self.Text = ""
        self.image_list = []

    def draw_background_grid(self): # 根据当前textFile设置在背景中绘制方格和尺寸
        self.Text_background = Image.new(mode="L", size=(self.Text_background_x, self.Text_background_y), color=255)
        draw = ImageDraw.Draw(self.Text_background)     # 允许在imageTemp图片上画画
        draw.line([(self.Text_left_margin, self.Text_top_margin),
                   (self.Text_background_x - self.Text_right_margin, self.Text_top_margin)],
                  fill=230, width=3 * self.Grid // 10)       # 上边框
        draw.line([(self.Text_left_margin, self.Text_top_margin),
                   (self.Text_left_margin, self.Text_background_y - self.Text_bottom_margin)],
                  fill=230, width=3 * self.Grid // 10)  # 左边框
        draw.line([(self.Text_background_x - self.Text_right_margin, self.Text_top_margin),
                   (self.Text_background_x - self.Text_right_margin, self.Text_background_y - self.Text_bottom_margin)],
                  fill=230, width=3 * self.Grid // 10)  # 右边框
        draw.line([(self.Text_left_margin, self.Text_background_y - self.Text_bottom_margin),
                   (self.Text_background_x - self.Text_right_margin, self.Text_background_y - self.Text_bottom_margin)],
                  fill=230, width=3 * self.Grid // 10)  # 下边框
        for i in range(1, (self.Text_background_y - self.Text_top_margin - self.Text_bottom_margin) // self.Text_line_spacing + 1):
            draw.line([(self.Text_left_margin, self.Text_top_margin + i * self.Text_line_spacing),
                       (self.Text_background_x - self.Text_right_margin, self.Text_top_margin + i * self.Text_line_spacing)],
                      fill=230, width=3 * self.Grid // 10)
            draw.line([(self.Text_left_margin, self.Text_top_margin + i * self.Text_line_spacing - self.Text_font_size),
                       (self.Text_background_x - self.Text_right_margin,
                        self.Text_top_margin + i * self.Text_line_spacing - self.Text_font_size)],
                      fill=230, width=3 * self.Grid // 10)
            for j in range(1, int(self.Text_background_x - self.Text_left_margin - self.Text_right_margin) //
                              int(self.Text_font_size + self.Text_word_spacing) + 1):
                draw.line(
                    [(self.Text_left_margin + j * (self.Text_font_size + self.Text_word_spacing),
                      self.Text_top_margin + i * self.Text_line_spacing - self.Text_font_size),
                     (self.Text_left_margin + j * (self.Text_font_size + self.Text_word_spacing),
                      self.Text_top_margin + i * self.Text_line_spacing)],
                    fill=230, width=3 * self.Grid // 10)
                draw.line(
                    [(self.Text_left_margin + j * (self.Text_font_size + self.Text_word_spacing) - self.Text_word_spacing,
                      self.Text_top_margin + i * self.Text_line_spacing - self.Text_font_size),
                     (self.Text_left_margin + j * (self.Text_font_size + self.Text_word_spacing) - self.Text_word_spacing,
                      self.Text_top_margin + i * self.Text_line_spacing)],
                    fill=230, width=3 * self.Grid // 10)

    def change_font(self, font: str):
        self.Text_font_dir = font

    def draw_background_white(self):
        # self.Text_background = Image.new(mode="1", size=(self.Text_background_x, self.Text_background_y), color=1)
        self.Text_background = Image.open("D:/Miniconda3/envs/pyQtApp_00/Data/grbl_Writter/backgrounds/background_02.jpg")

    def load_txt(self, dir):
        self.Text = open(dir, 'r', encoding='UTF-8').read()

    def upgrade_settings(self): # 应用textFile设置
        self.Template_file = Template(
            background=self.Text_background,
            font=ImageFont.truetype(self.Text_font_dir, size=self.Text_font_size),
            line_spacing=self.Text_line_spacing,  # 行高度
            fill=0,  # 字体“颜色”
            left_margin=self.Text_left_margin + int(self.Text_x_Adjust * self.Text_font_size),  # 左边距
            top_margin=self.Text_top_margin - int(self.Text_y_Adjust * self.Text_font_size),  # 上边距
            right_margin=self.Text_right_margin,  # 右边距
            bottom_margin=self.Text_bottom_margin,  # 下边距
            word_spacing=self.Text_word_spacing,  # 字间距
            line_spacing_sigma=self.Text_line_spacing_sigma,  # 行间距随机扰动
            font_size_sigma=self.Text_font_size_sigma,  # 字体大小随机扰动
            word_spacing_sigma=self.Text_word_spacing_sigma,  # 字间距随机扰动
            end_chars=self.Text_end_chars,  # 防止特定字符因排版算法的自动换行而出现在行首
            perturb_x_sigma=self.Text_perturb_x_sigma,  # 笔画横向偏移随机扰动
            perturb_y_sigma=self.Text_perturb_y_sigma,  # 笔画纵向偏移随机扰动
            perturb_theta_sigma=self.Text_perturb_theta_sigma,  # 笔画旋转偏移随机扰动
        )

    def img_Show(self): # 调用handwrite并对返回结果进行逐张预览
        with Pool() as p: # 提升15s
            images = handwrite(self.Text, self.Template_file, mapper=p.map)
        self.image_list = []

        for im in images:
            assert isinstance(im, Image.Image)
            self.image_list.append(im)
            # im.show()

        return self.image_list

    def img_save(self, filename: str):
        if (len(self.image_list) != 0):
            for i, im in enumerate(self.image_list):
                assert isinstance(im, Image.Image)
                num = filename.find('.')
                im.save(filename[:num] + f"_{i}" + filename[num:])


if __name__ == '__main__':

    text_class = Text(10)

    text_class.load_txt("D:/Miniconda3/envs/pyQtApp_00/Data/grbl_Writter/texts/C51_test_4.txt")
    # text_class.Text = "36.1\n36.1\n36.1\n"

    text_class.draw_background_white()

    text_class.upgrade_settings()

    text_class.img_Show()

    text_class.img_save("D:/Videos/Captures/Screenshot 2022-09-23 160202.png")
